//
//  PlayViewController.m
//  TravelEveryDay
//
//  Created by 路洪宇 on 15/10/15.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "PlayViewController.h"
#import "LocationViewController.h"
#import "PlayScreenViewController.h"
#import "PlayUserViewController.h"
#import "BaseHeader.h"
#import "DataBase.h"
@interface PlayViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong)UIButton *titleButton;

@end

@implementation PlayViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
#pragma mark - 读取沙盒文件,已选择标签数组
    NSString *home = NSHomeDirectory();
    NSString * docpath = [home stringByAppendingPathComponent:@"Documents"];
    NSString * filepath = [docpath stringByAppendingPathComponent:@"data.plist"];
    _tempTitleArr = [NSMutableArray arrayWithContentsOfFile:filepath];
    if (_tempTitleArr.count == 0) {
        _titleStr = @"城市猎人带你玩";
    }
    else
    {
        //将数组转为字符串
        _tempTitle = [_tempTitleArr componentsJoinedByString:@"·"];
        _titleStr = _tempTitle;
    }
    [self setTitleView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    _lastCount = 0;
    self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    [[UINavigationBar appearance] setBarTintColor:[UIColor blackColor]];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    [[self navigationController] setNavigationBarHidden:YES animated:NO];
    _playArray = [[NSMutableArray alloc]init];
    _bigArray = [[NSMutableArray alloc] init];
    _initialStr = @"北京";
    [self setUpTableView];
    [self setUpFooterView];
    
    
    [self header];
    //判断网络调取获取数据方法
    if ([self haveOrNot] == NO) {
        [self getLocalData];
    }else{
    }

}

#pragma mark - 判断网络状态
-(BOOL)haveOrNot
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            return NO;
            break;
        case ReachableViaWWAN:
            return YES;
            break;
        case ReachableViaWiFi:
            return YES;
            break;
    }
    
}

#pragma mark - 城市代理方法
-(void)giveLocation:(NSString *)location
{
    _initialStr = location;
    [self header];
    //读取沙盒文件,标签数组,当切换城市后将标签数组清零,重置title
    NSString *home = NSHomeDirectory();
    NSString * docpath = [home stringByAppendingPathComponent:@"Documents"];
    NSString * filepath = [docpath stringByAppendingPathComponent:@"data.plist"];
    _tempTitleArr = [NSMutableArray arrayWithContentsOfFile:filepath];
    [_tempTitleArr removeAllObjects];
    [_tempTitleArr writeToFile:filepath atomically:YES];
    _titleStr = @"城市猎人带你玩";
    [self setTitleView];
    
}

#pragma mark - 标签 数组排序代理方法
-(void)giveSort:(NSString *)sort
{
    //排序
    if ([sort isEqualToString:@"人气最高"]) {
        //构建排序描述器
        NSSortDescriptor *personAgeDesc = [NSSortDescriptor sortDescriptorWithKey:@"like_count" ascending:NO];
        NSArray *descriptorArray = [NSArray arrayWithObjects:personAgeDesc, nil];
        //把排序描述器放进数组里，放入的顺序就是你想要排序的顺序
        NSArray *sortedArray = [_playArray sortedArrayUsingDescriptors: descriptorArray];
        _playArray = [NSMutableArray arrayWithArray:sortedArray];
    }
    else
    {
        _playArray = _bigArray;
    }
    [_playTableView reloadData];
}

#pragma mark - 标签 种类代理方法
-(void)giveScreen:(NSMutableArray *)screenAry
{
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    for (PlayModel *tempModel in _bigArray) {
        for (NSString *tempStr in screenAry) {
            if ([tempModel.tab_list containsObject:tempStr])
            {
                if (![tempArray containsObject:tempModel]) {
                    [tempArray addObject:tempModel];
                }
            }
        }
    }
    if (tempArray.count != 0) {
        _playArray = tempArray;
        //将数组以·为接口拼接数组里字符串成字符串
        NSString *string = [screenAry componentsJoinedByString:@"·"];
        _titleStr = string;
    }
    else
    {
        _playArray = _bigArray;
        _titleStr = @"城市猎人带你玩";
    }
    [_playTableView reloadData];
}

#pragma mark - Set Header View
-(void)setTitleView
{
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    [titleView setBackgroundColor:TITLECOLOR];
    [self.view addSubview:titleView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2-90, 25, 180, 32)];
    
    titleLabel.text = _titleStr;
    [titleLabel setTextAlignment:NSTextAlignmentCenter];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont systemFontOfSize:19.];
    [titleView addSubview:titleLabel];
    
    _titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_titleButton setTitle:_initialStr forState:UIControlStateNormal];
    [_titleButton.titleLabel setTextAlignment:NSTextAlignmentLeft];
    [_titleButton setImage:[UIImage imageNamed:@"play-xl.png"] forState:UIControlStateNormal];
    _titleButton.titleLabel.font = [UIFont systemFontOfSize:16.];
    [_titleButton addTarget:self action:@selector(placeClick) forControlEvents:UIControlEventTouchUpInside];
    [_titleButton setFrame:CGRectMake(10, 27, 50, 30)];
    [titleView addSubview:_titleButton];
    
    UIButton *screenButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [screenButton setFrame:CGRectMake(SCREEN_WIDTH-50, 25, 40, 30)];
    [screenButton setTitle:@"筛选" forState:UIControlStateNormal];
    screenButton.titleLabel.font = [UIFont systemFontOfSize:16.];
    [screenButton addTarget:self action:@selector(screenClick) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:screenButton];
    
    
}

#pragma mark- Info Method
- (void)header
{
    __block PlayViewController *playView = self;
    [self.playTableView addLegendHeaderWithRefreshingBlock:^{
        
        playView.playPage = 1;
        playView.playIsLoading = NO;
        [playView aFNdata:playView.playPage isOrNo:NO];
    }];
    [self.playTableView.header beginRefreshing];
}

- (void)aFNdata:(NSInteger)page isOrNo:(BOOL)loading
{
    NSString *urlStr = [[NSString stringWithFormat:@"http://api.breadtrip.com/hunter/products/more/?city_name=%@&list[]=%%3CBTCityHunterItemModel%%3A%%200x157c2e30%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x15729fc0%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x157cb460%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x157c0fd0%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x15769d40%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x1579a610%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x155c4d80%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x1571cc50%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x15726200%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x155db1e0%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x155fb920%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x1572eb30%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x157ab080%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x155d81a0%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x157476f0%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x157c49c0%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x157c6d10%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x1559c670%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x15737470%%3E&list[]=%%3CBTCityHunterItemModel%%3A%%200x1573abb0%%3E&sign=965cede0f3f259dfcec7f50f54ee26ea&start=0",_initialStr]stringByAddingPercentEncodingWithAllowedCharacters :[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [AFNDataBlock string:urlStr AFNData:^(id block) {
        if (loading == NO) {
            [self.playArray removeAllObjects];
        }
        for (NSMutableDictionary *dic in [block objectForKey:@"product_list"])
        {
            PlayModel *model = [PlayModel modelWithDictionary:dic];
            model.userId = [[dic objectForKey:@"user"] objectForKey:@"id"];
            model.avatar_l = [[dic objectForKey:@"user"] objectForKey:@"avatar_l"];
            model.name = [[dic objectForKey:@"user"] objectForKey:@"name"];
            [_playArray addObject:model];
        }
        
        NSString *documentString = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSLog(@"沙盒路径 = %@",documentString);
        
        NSString *pathString = [documentString stringByAppendingString:@"/play.av"];
        
        //针对复杂对象,例如model类,写入本地文件需要对对象进行归档(序列化)操作,读取时需要反归档(反序列化)
        //归档(序列化)就是实现NSCoding协议
        
        //归档文件写入
        BOOL aaa = [NSKeyedArchiver archiveRootObject:_playArray toFile:pathString];
        if (aaa) {
            NSLog(@"成功");
        }
    
        _bigArray = _playArray;
        [self.playTableView.header endRefreshing];
        [self.playTableView.footer endRefreshing];
        
        [self.playTableView reloadData];
        
        
    }];
    _titleStr = @"城市猎人带你玩";
    [self setTitleView];

    //当再次刷新数据是将筛选数据清除,刷新后是全部数据
    NSString *home = NSHomeDirectory();
    NSString * docpath = [home stringByAppendingPathComponent:@"Documents"];
    NSString * filepath = [docpath stringByAppendingPathComponent:@"data.plist"];
    _tempTitleArr = [NSMutableArray arrayWithContentsOfFile:filepath];
    [_tempTitleArr removeAllObjects];
    [_tempTitleArr writeToFile:filepath atomically:YES];
    
}


-(void)getLocalData
{
    NSString *documentString = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"沙盒路径 = %@",documentString);
    
    NSString *pathString = [documentString stringByAppendingString:@"/play.av"];
    _playArray = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:pathString]];
    _bigArray = _playArray;

    [self.playTableView reloadData];
    [self.playTableView.header endRefreshing];
    
}

#pragma mark - Set Up TableView
-(void)setUpTableView
{
    _playTableView  = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH, SCREEN_HEIGHT-40) style:UITableViewStylePlain];
    _playTableView.delegate = self;
    _playTableView.dataSource = self;
    _playTableView.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    [_playTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:_playTableView];
    
}

#pragma mark - Set Up FooterView
-(void)setUpFooterView
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    footerView.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 40)];
    footerLabel.text = @"－· 你的生活 我的旅行 ·－";
    footerLabel.textAlignment = NSTextAlignmentCenter;
    footerLabel.textColor = [UIColor colorWithRed:0.88 green:0.84 blue:0.73 alpha:1];
    footerLabel.backgroundColor =[UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    [footerView addSubview:footerLabel];
    [_playTableView setTableFooterView:footerView];
}

#pragma mark- TableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.playArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 330*HEIGHT;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"playTableViewCell";
    PlayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil)
    {
        cell = [[PlayTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.avatar_lImageButton addTarget:self action:@selector(avatar_ButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.avatar_lImageButton setTag:indexPath.row];

    PlayModel *data = [self.playArray objectAtIndex:indexPath.row];
    self.playTableView.scrollsToTop = YES;
    [cell getInfo:data];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PlayDetailViewController *playDetailVC = [[PlayDetailViewController alloc] init];
    playDetailVC.tempModel = [self.playArray objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:playDetailVC animated:YES];
}

-(void)placeClick
{
    LocationViewController *locationVC = [[LocationViewController alloc] init];
    locationVC.delegate = self;
    
    [self presentViewController:locationVC animated:YES completion:^{
        
    }];
    
}

-(void)screenClick
{
    PlayScreenViewController *screenVC = [[PlayScreenViewController alloc] init];
    screenVC.delegate = self;
    [self presentViewController:screenVC animated:YES completion:^{
    }];
}

-(void)avatar_ButtonClick:(UIButton *)sender
{
    PlayUserViewController *userVC = [[PlayUserViewController alloc] init];
    [self.navigationController pushViewController:userVC animated:YES];
    userVC.tempModel = [self.playArray objectAtIndex:sender.tag];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
